//
//  QRCodeViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/3.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "QRCodeViewController.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <ShareSDK/ShareSDK.h>
#import <MessageUI/MessageUI.h>
#import <MailConnection/MailConnection.h>

#define kLineNum        4
#define kShareTag       100
#define kShareMoreTag   200
@interface QRCodeViewController ()<HTTPClientDelegate>
{
    UIScrollView *_scrollView;
    
    UIImageView *_codeImageView;
    NSMutableArray *_shareImageArray;
    NSMutableArray *_shareTitleArray;
    
    NSString *_promoteImg;
    NSString *_spreadLink;
}
@property(nonatomic ,strong) NetWorkClient *requestClient;
@end

@implementation QRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if(iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self initNavBarTitle:@"我的二维码" andLeftItemName:@"返回" andRightItemName:@""];
    
    [self initData];
    [self initView];
}

#pragma mark - Action
- (void)dealShareMoreTap:(UITapGestureRecognizer *)tap {
    
    NSInteger index = tap.view.tag - kShareMoreTag;
    if ([_shareTitleArray[index] isEqualToString:@"微信"] || [_shareTitleArray[index] isEqualToString:@"朋友圈"]) {
        if (![WXApi isWXAppInstalled]) {
            [SVProgressHUD showErrorWithStatus:@"您尚未安装该应用"];
            return;
        }
    }
    if ([_shareTitleArray[index] isEqualToString:@"QQ"] || [_shareTitleArray[index] isEqualToString:@"QQ空间"]) {
        if (![QQApiInterface isQQInstalled]) {
            [SVProgressHUD showErrorWithStatus:@"您尚未安装该应用"];
            return;
        }
    }
    if ([_shareTitleArray[index] isEqualToString:@"短信"]) {
        // 判断用户设备能否发送短信
        if (![MFMessageComposeViewController canSendText]) {
            [SVProgressHUD showErrorWithStatus:@"该设备不支持发送短信"];
            return;
        }
    }
    if ([_shareTitleArray[index] isEqualToString:@"邮件"]) {
        // 1. 先判断能否发送邮件
        if (![MFMailComposeViewController canSendMail]) {
            // 提示用户设置邮箱
            [SVProgressHUD showErrorWithStatus:@"该设备不支持邮件分享或尚未设置邮件帐号"];
            return;
        }
    }
    
    ShareType shareType = ShareTypeWeixiSession;
    switch (index) {
        case 0:
            shareType = ShareTypeWeixiSession;
            break;
        case 1:
            shareType = ShareTypeWeixiTimeline;
            break;
        case 2:
            shareType = ShareTypeQQ;
            break;
        case 3:
            shareType = ShareTypeSinaWeibo;
            break;
        case 4:
            shareType = ShareTypeQQSpace;
            break;
        case 5:
            shareType = ShareTypeSMS;
            break;
        case 6:
            shareType = ShareTypeMail;
            break;
        default:
            shareType = ShareTypeWeixiSession;
            break;
    }
    
    [self shareDataWithShareType:shareType];
}

- (void)shareDataWithShareType:(ShareType)shareType {
    //构造分享内容
    NSString *url;
    if (AppDelegateInstance.userInfo.spreadLink.length > 0) {
        url = AppDelegateInstance.userInfo.spreadLink;
    }else {
        url = [NSString stringWithFormat:@"%@/app/share",Baseurl];
    }
    
    id<ISSContent> publishContent;
    if (_promoteImg.length > 0) {
        publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@%@",@"随取宝app全新面世!随存随取 8秒注册赢好礼!",url]
                            defaultContent:@""
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"app_logo"]]
                                     title:@"随取宝送大礼了！"
                                       url:url
                               description:@""
                                 mediaType:SSPublishContentMediaTypeNews];
    }else {
        publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@%@",@"随取宝app全新面世!随存随取 8秒注册赢好礼!",url]
                            defaultContent:@""
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"app_logo"]]
                                     title:@"随取宝送大礼了！"
                                       url:url
                               description:@""
                                 mediaType:SSPublishContentMediaTypeNews];
    }
    
    [ShareSDK shareContent:publishContent
                      type:shareType
               authOptions:nil
              shareOptions:nil
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state,
                             id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        if (state == SSResponseStateSuccess) {
                            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"分享成功", nil)];
                            DLOG(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                        }else if (state == SSResponseStateFail) {
                            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"分享失败", nil)];
                            DLOG(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                        }else {
                        }
                    }];
}


- (void)initData {
    _shareImageArray = [[NSMutableArray alloc] initWithArray:@[@"Share_WeChat",@"Share_WeChat_Circle",@"Share_QQ",@"Share_WeiBo",@"Share_QQZone",@"Share_Message",@"Share_Mail"]];
    _shareTitleArray = [[NSMutableArray alloc] initWithArray:@[@"微信",@"朋友圈",@"QQ",@"微博",@"QQ空间",@"短信",@"邮件"]];
    
    [self requestData];
}

/**
 加载数据
 */
- (void)requestData {
    if (_promoteImg.length > 0 && _spreadLink.length > 0) {
        return;
    }
    
    if (AppDelegateInstance.userInfo == nil) {
        [ReLogin outTheTimeRelogin:self];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:@"28" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma mark HTTPClientDelegate 网络数据回调代理
-(void) startRequest
{
   
    
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    NSDictionary *dics = obj;
    DLOG(@"dics -> %@", dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if ([dics objectForKey:@"promoteImg"] && ![[dics objectForKey:@"promoteImg"] isKindOfClass:[NSNull class]]) {
            NSString *promoteImg = [NSString stringWithFormat:@"%@",[dics objectForKey:@"promoteImg"]];
            if (![promoteImg hasPrefix:@"http"]) {
                if ([Baseurl isEqualToString:@"http://p2p-7.test2.wangdai.me/sp2p_tss"]) {
                    _promoteImg = [NSString stringWithFormat:@"%@%@",@"http://p2p-7.test2.wangdai.me",promoteImg];
                }else {
                    _promoteImg = [NSString stringWithFormat:@"%@%@",Baseurl,promoteImg];
                }
            }
        }
        if ([dics objectForKey:@"spreadLink"] && ![[dics objectForKey:@"spreadLink"] isKindOfClass:[NSNull class]]) {
            _spreadLink = [NSString stringWithFormat:@"%@",[dics objectForKey:@"spreadLink"]];
        }
        [_codeImageView sd_setImageWithURL:[NSURL URLWithString:_promoteImg] placeholderImage:KDefaultImage];
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
        
    }else {
        DLOG(@"返回失败  msg -> %@",[obj objectForKey:@"msg"]);
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [obj objectForKey:@"msg"]]];
    }
}

// 返回失败
-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    
}

// 无可用的网络
-(void) networkError{
    
}


#pragma mark - View
- (void)initView {
    _scrollView = [UIScrollView scrollViewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 64) delegate:self backgroundColor:[UIColor whiteColor] superview:self.view];
    
    UILabel *value1 = [UILabel labelWithFrame:RECTMAKE(10, KAdaptNum(10), MSWIDTH - 20, KAdaptNum(20)) text:@"1.让朋友手机扫描下面的二维码即可注册随取宝：" textColor:KGrayColor textFont:12 fitWidth:YES superview:_scrollView];
    
    UIView *codeView = [UIView viewWithFrame:RECTMAKE(MSWIDTH/4, GetMaxY(value1) + KAdaptNum(20), MSWIDTH/2, MSWIDTH/2) backgroundColor:nil superview:_scrollView];
    codeView.layer.borderColor = KColor.CGColor;
    codeView.layer.borderWidth = kLineHeight;
    codeView.layer.cornerRadius = 8.0f;
    
    _codeImageView = [UIImageView imageViewWithFrame:RECTMAKE(10, KAdaptNum(10), GetWidth(codeView) - 20, GetHeight(codeView) - KAdaptNum(20)) imageFile:@"" superview:codeView];
    _codeImageView.image = KDefaultImage;
    
    UILabel *value2 = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(codeView) + KAdaptNum(20), MSWIDTH - 20, KAdaptNum(20)) text:@"2.还可以通过以下几种方式分享给朋友：" textColor:KGrayColor textFont:12 fitWidth:YES superview:_scrollView];
    
    CGFloat originY = GetMaxY(value2);
    
    for (NSInteger i=0; i < _shareImageArray.count; i++) {
        CGFloat w = MSWIDTH/kLineNum;
        CGFloat h = KAdaptNum(70);
        CGFloat x = (i%kLineNum) * w;
        CGFloat y = GetMaxY(value2) + KAdaptNum(20) + (i/kLineNum) * h;
        
        UIView *backView = [UIView viewWithFrame:CGRectMake(x, y, w, h) backgroundColor:nil superview:_scrollView];
        backView.tag = kShareMoreTag + i;
        [backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealShareMoreTap:)]];
        
        originY = GetMaxY(backView);
        
        UIImageView *imageView = [UIImageView imageViewWithFrame:CGRectMake((backView.frame.size.width - KAdaptNum(36))/2, 0, KAdaptNum(36), KAdaptNum(36)) imageFile:_shareImageArray[i] superview:backView];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.userInteractionEnabled = YES;
        
        UILabel *label = [UILabel labelWithFrame:CGRectMake(10, CGRectGetMaxY(imageView.frame), backView.frame.size.width - 20, KAdaptNum(20)) text:_shareTitleArray[i] textColor:KBlackColor textFont:10.0 fitWidth:NO superview:backView];
        label.textAlignment = NSTextAlignmentCenter;
        label.userInteractionEnabled = YES;
        
        if ([_shareTitleArray[i] isEqualToString:@"微信"] || [_shareTitleArray[i] isEqualToString:@"朋友圈"]) {       //微信
            if (![WXApi isWXAppInstalled]) {
                label.textColor = KGrayColor;
            }
        }
        if ([_shareTitleArray[i] isEqualToString:@"QQ"] || [_shareTitleArray[i] isEqualToString:@"QQ空间"]) {
            if (![QQApiInterface isQQInstalled]) {
                label.textColor = KGrayColor;
            }
        }
    }
    
    _scrollView.contentSize = CGSizeMake(0, originY + 20);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
